package org.itzheng.yuezhi.utils.comm;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广播接受者的工具类
 * Created by admin on 2017/8/13.
 */

public class BlueToothBroadcastReceiverUtils {
    /**
     * 开始查找蓝牙设备
     */
    public void restartDiscovery() {
        cancelDiscovery();
        //并重新开始
        BlueToothUtils.startDiscovery();
    }

    public void cancelDiscovery() {
        // 关闭再进行的服务查找
        if (BlueToothUtils.isDiscovering()) {
            BlueToothUtils.cancelDiscovery();
        }
    }

    private static Map<Object, BlueToothBroadcastReceiverUtils> utilsMap = new HashMap<>();

    public static BlueToothBroadcastReceiverUtils getInstance(Object tag) {
        BlueToothBroadcastReceiverUtils instance = null;
        if (tag != null) {
            instance = utilsMap.get(tag);
            if (instance == null) {
                instance = new BlueToothBroadcastReceiverUtils();
                utilsMap.put(tag, instance);
            }
        } else {
            instance = new BlueToothBroadcastReceiverUtils();
        }
        return instance;
    }

    //    private OnMinuteChangeListener mListener;
    List<OnSearchBluetoothListener> listeners = new ArrayList<>();

    /**
     * 设置广播监听
     *
     * @param onSearchBluetoothListener
     */
    public void addOnSearchBluetoothListener(OnSearchBluetoothListener onSearchBluetoothListener) {
        if (onSearchBluetoothListener != null) {
            if (!listeners.contains(onSearchBluetoothListener)) {
                listeners.add(onSearchBluetoothListener);
            }
        }
    }

    public static void removeInstance(Object tag) {
        if (tag != null) {
            if (utilsMap.get(tag) != null) {
                utilsMap.get(tag).unregisterReceiver();
                utilsMap.get(tag).clearOnSearchBluetoothListener();

                utilsMap.remove(tag);
            }
        }
    }

    private void clearOnSearchBluetoothListener() {
        listeners.clear();
    }

    /**
     * 注册广播
     */
    public void registerReceiver() {
        // 注册接收查找到设备action接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
        // 开始
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
        //结束
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
        //蓝牙打开关闭监听
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
        //连接状态监听，连接
        filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
        //断开连接
        filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        UIUtils.getContext().registerReceiver(mReceiver, filter);
    }

    /**
     * 反注册广播监听
     */
    public void unregisterReceiver() {
        try {
            UIUtils.getContext().unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 蓝牙搜索监听
     */
    public interface OnSearchBluetoothListener {
        /**
         * 开始搜索
         */
        void discoveryStart();

        /**
         * 搜索结束
         */
        void discoveryFinish();

        /**
         * 已绑定设备
         *
         * @param device
         */
        void foundBonded(BluetoothDevice device);

        /**
         * 未绑定设备
         *
         * @param device
         */
        void foundNoBond(BluetoothDevice device);

    }


    /**
     * 查找到设备和搜索完成action监听器
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        private static final String TAG = "BlueToothBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "onReceive:" + action);
            switch (action) {
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    for (OnSearchBluetoothListener mListener : listeners)
                        if (mListener != null) {
                            mListener.discoveryStart();
                        }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    for (OnSearchBluetoothListener mListener : listeners)
                        if (mListener != null) {
                            mListener.discoveryFinish();
                        }
                    break;
                case BluetoothDevice.ACTION_FOUND:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                        for (OnSearchBluetoothListener mListener : listeners)
                            if (mListener != null) {
                                mListener.foundBonded(device);
                            }
                    } else {
                        for (OnSearchBluetoothListener mListener : listeners)
                            if (mListener != null) {
                                mListener.foundNoBond(device);
                            }
                    }
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    Log.d(TAG, "ACTION_BOND_STATE_CHANGED");
                    break;
            }
        }
    };
}
